import { defineStore } from 'pinia';
import { store } from '@/store';
import { miniProgramConfig, shareImgList, tabbarList } from '@/api/dynamicAllocation';
import { CacheEnum } from '@/enums/cacheEnum';
import { DynamicTabbarPagesEnum, TabbarPageEnum } from '@/enums/pageEnum';
import type { HomeTabResult } from '@/api/dynamicAllocation/types';
import { ShareTypeEnum } from '@/enums/shareEnum';
import { ConfigRouterTypeEnum } from '@/enums/configRouterTypeEnum';
import type { ContactsConfigResult } from '@/api/contactsMap/types';
import { requestContactsConfig } from '@/api/contactsMap';
import { Toast } from '@/utils';
import { toAIminiProgram, toHuibangCloud } from '@/utils/dynamicConfig';

/**
* @description 动态获取tabbarList
* @date 29/11/2023
* @param {HomeTabResult[]} [records]
*/
export function getTabbarList(records: HomeTabResult[]) {
  let list: ITabbarItem[] = [];
  records.forEach((item, index) => {
    let pagePath = '';
    switch (index) {
      case 0:
        pagePath = TabbarPageEnum.BASE_HOME;
        break;
      case records.length - 1:
        pagePath = TabbarPageEnum.BASE_MINE;
        break;
      default:
        pagePath = index <= 3 ? `puppetTaabarPage_${index}` : '';
        break;
    }

    let obj: ITabbarItem = {
      index,
      text: item.name,
      iconPath: item.iconUrl,
      selectedIconPath: item.iconSelectedUrl,
      pagePath,
      component: item.linkUrl as DynamicTabbarPagesEnum,
      to: void 0
    };

    if (item.typeOptionsId === ConfigRouterTypeEnum.CLOUD_HOME) {
      obj.to = () => toHuibangCloud('storeHome', { type: 'home' })
    }
    if (item.typeOptionsId === ConfigRouterTypeEnum.AI_MINI_PROGRAM) {
      obj.to = () => toAIminiProgram('aiChatPage')
    }
    if (item.typeOptionsId === ConfigRouterTypeEnum.MINI_PROGRAM && item.appId) {
      obj.miniprogramOptions = {
        appId: item.appId,
        path: item.linkUrl,
      };
    }

    list.push({
      ...obj,
      // verify:
      //   item.linkUrl === TabbarPageEnum.BASE_MINE ||
      //   item.linkUrl === TabbarPageEnum.BASE_MEMBER ||
      //   item.linkUrl === TabbarPageEnum.BASE_CONTACTSMAP,
    });
  });
  return list
}

export interface ITabbarItem {
  index: number;
  pagePath: string; //傀儡页 路径
  component: DynamicTabbarPagesEnum; // 要加载的页面(提前配置在base中)
  h5Link?: string // H5外链地址
  text: string; //标题
  iconPath: string; //图标地址
  selectedIconPath: string; //选中图标地址
  hump?: boolean; //是否为凸起图标
  num?: number; //角标数量
  isDot?: boolean; //角标是否为圆点
  verify?: boolean; //是否验证  （如登录）
  // 跳转小程序的配置
  miniprogramOptions?: {
    appId: string;
    path?: string;
  };
  to?: () => void;
}

export interface GlobalConfig {
  /** 机构logo */
  logo: string;
  name: string;
  /** 普通分享通用配置 */
  comShareOptions: {
    shareImg: string;
    shareTitle: string;
  };
  /** 首屏图 */
  firstScreenFigure: string;
  /** 邀请入会海报主图 */
  posters: string;
  /** 公众号二维码 */
  officialAccounts: string;
  /** 用户协议及隐私协议 */
  userAgreement: string;
  /** 主题色 */
  themeColor: string;
  /** 商城APPID */
  mallAppId: string
  /** AI小程序APPID */
  aiAppId: string
  /** 是否开启AI */
  isEnableAi: number
  /** AI智能体UUID */
  aiBotUUID: string
}

interface AppState {
  tabbarData: HomeTabResult[]
  shareImgList: HomeTabResult[];
  globalConfig: GlobalConfig | null;
  canvasType: '2d' | 'webgl';
  /** 自定义header 是否显示 */
  isHeaderShow: boolean
  /** 人脉配置 */
  contactsConfig: ContactsConfigResult | null
  /** 显示/隐藏 隐私协议弹窗 */
  privacyPopupVisible: boolean
  /** 未同意隐私协议触发的回调resolve函数 */
  resolvePrivacyAuthorization: ((...args: any[]) => any) | null
  /** 是否是从特殊场景(分享朋友圈, 复制链接)进入小程序 */
  isSpecialScenario: boolean;
}

export const useAppStore = defineStore({
  id: 'app',
  state: (): AppState => ({
    tabbarData: uni.getStorageSync(CacheEnum.tabbar) || [],
    globalConfig: uni.getStorageSync(CacheEnum.globalConfig) || null,
    shareImgList: uni.getStorageSync(CacheEnum.shareImgList) || [],
    canvasType: '2d',
    isHeaderShow: true,
    contactsConfig: null,
    privacyPopupVisible: false,
    resolvePrivacyAuthorization: null,
    isSpecialScenario: false
  }),
  getters: {
    tabbarList: (state) => getTabbarList(state.tabbarData),
  },
  actions: {
    /** 查询隐私授权情况 */
    getPrivacySetting() {
      return new Promise((resolve, reject) => {
        if (wx.getPrivacySetting) {
          wx.getPrivacySetting({
            success: res => {
              if (res.needAuthorization) {
                this.setPrivacyPopupVisible(true)
                reject()
              } else {
                resolve(true)
              }
            }
          })
        } else {
          resolve(true)
        }
      })
    },
    /** 显示隐私弹窗 */
    setPrivacyPopupVisible(bol: boolean) {
      this.privacyPopupVisible = bol
    },
    /** 设置隐私回调 */
    setResolvePrivacyAuthorization(fnc: (...args: any[]) => any) {
      this.resolvePrivacyAuthorization = fnc
    },
    /**
     * @description 显示自定义头
     * @date 27/03/2023
     */
    showHeader() {
      this.isPc() && (this.isHeaderShow = true)
    },
    /**
     * @description 隐藏自定义头
     * @date 27/03/2023
     */
    hideHeader() {
      this.isPc() && (this.isHeaderShow = false)
    },
    /**
     * @description 获取小程序Tabbar菜单
     * @date 02/08/2022
     * @returns {*}  {Promise<ITabbarItem[]>}
     */
    tabbarApi(): Promise<ITabbarItem[]> {
      return new Promise(async (relovse, reject) => {
        try {
          const { records } = await tabbarList();
          const list = getTabbarList(records);
          this.tabbarData = records
          uni.setStorageSync(CacheEnum.tabbar, records);
          relovse(list);
        } catch (error) {
          reject(error);
        }
      });
    },

    /**
     * @description 获取分享图列表
     * @date 27/09/2022
     */
    async getShareImgList() {
      const { records } = await shareImgList();
      const localData = [] as any[]
      const item = records.find(v => v.shareType === ShareTypeEnum.invitationToFillOutServiceForm)
      if (!item) {
        localData.push({
          name: '邀请填写服务表单',
          iconUrl: 'https://hb-saas.obs.cn-south-1.myhuaweicloud.com/saas_share/service_ticke_share.jpg',
          shareType: ShareTypeEnum.invitationToFillOutServiceForm
        })
      }
      this.shareImgList = [
        ...localData,
        ...records
      ];
      uni.setStorageSync(CacheEnum.shareImgList, records);
    },

    /**
     * @description 查询分享图配置
     * @date 27/09/2022
     * @param {ShareTypeEnum} shareType
     */
    hasShareImgConfig(shareType: ShareTypeEnum) {
      return this.shareImgList.find((v) => v.shareType === shareType);
    },

    /**
     * @description 获取小程序基础信息
     * @date 11/08/2022
     */
    getAccountInfoSync() {
      // #ifdef MP
      const { miniProgram } = uni.getAccountInfoSync();
      this.canvasType = this.isPc() ? 'webgl' : '2d';
      uni.setStorageSync(CacheEnum.appid, miniProgram.appId);
      uni.setStorageSync(CacheEnum.envVersion, miniProgram.envVersion);
      return miniProgram
      // #endif
      // #ifndef MP
      return {}
      // #endif
    },

    /**
     * @description 判断是否是pc端微信
     * @date 08/12/2022
     * @returns {boolean}
     */
    isPc(): Boolean {
      const pc = ['mac', 'windows'];
      let res = uni.getDeviceInfo()
      if (!res || !res?.platform) res = uni.getSystemInfoSync()

      return pc.includes(res?.platform);
    },

    /**
     * @description 获取小程序全局配置
     * @date 02/08/2022
     */
    async miniProgramConfig() {
      this.getAccountInfoSync()
      await this.getShareImgList();
      const {
        logo,
        name,
        shareImgUrl,
        shareTitle,
        indexImgUrl,
        posters,
        officialAccounts,
        userAgreement,
        themeColor,
        mallAppId,
        aiAppId,
        isEnableAi,
        aiBotUUID
      } = await miniProgramConfig();
      this.globalConfig = {
        name,
        logo,
        comShareOptions: {
          shareImg: shareImgUrl,
          shareTitle: shareTitle,
        },
        firstScreenFigure: indexImgUrl,
        posters,
        officialAccounts,
        userAgreement,
        themeColor: themeColor || '#74A8FF',
        mallAppId,
        aiAppId,
        isEnableAi,
        aiBotUUID
      };
      uni.setStorageSync(CacheEnum.globalConfig, this.globalConfig);
      return this.globalConfig;
    },

    /**
     * @description 获取人脉功能相关配置
     * @date 10/03/2023
     */
    async getContactsConfig(): Promise<ContactsConfigResult> {
      const res = await requestContactsConfig()
      if (res?.connectionListShow && res?.unitListShow) {
        Toast('人脉配置错误')
        return Promise.reject('人脉配置错误')
      }
      this.contactsConfig = res
      return res
    },
    /**
  * @description 设置是否是特殊场景进入
  * @date 16/11/2022
  * @param bol
  */
    setIsSpecialScenario(bol: boolean) {
      this.isSpecialScenario = bol;
    },
  },
});

export function useAppStoreWithOut() {
  return useAppStore(store);
}
